#include	"csv.h"
#include	<cstdio>
#include	<cstring>

#define		CSV_LINE_MAX	8192

bool CsvFile::Load(const std::string & path, int header /* = 0 */, char delimiter /* = '\t' */) {
	if (path.empty()) return false;

	FILE * file = nullptr;

#if defined(_WIN32)
	if (fopen_s(&file, path.c_str(), "r") != 0) return false;
#else
	if ((file = fopen(path.c_str(), "r")) == NULL) return false;
#endif

	_header.clear();
	_data.clear();

	/// Check UTF-8 With bomb
	{
		unsigned char bomb[3] = { 0, 0, 0 };
		size_t count = fread(bomb, 1, 3, file);
		if (count < 3 || !(bomb[0] == 0xEF && bomb[1] == 0xBB && bomb[2] == 0xBF))
			fseek(file, 0, SEEK_SET);
	}

	char line[CSV_LINE_MAX] = { 0 };
	std::string delim(1, delimiter);

	/** Ignore all data before header line */
	for (int i = 0; i < header; ++i) {
		fgets(line, CSV_LINE_MAX, file);
		if (feof(file)) {
			fclose(file);
			return true;
		}
	}

	/** Read headers */
	memset(line, 0, CSV_LINE_MAX);
	fgets(line, CSV_LINE_MAX, file);
	_header = Split(TrimEnd(line), delim, false);

	/** Read datas */
	while (!feof(file)) {
		memset(line, 0, CSV_LINE_MAX);
		fgets(line, CSV_LINE_MAX, file);

		std::string record = TrimEnd(line);
		if (record.find_first_not_of(delim) == std::string::npos) continue;

		std::vector<std::string> values = Split(record, delim, false);
		_data.push_back(values);
	}

	fclose(file);
	return true;
}
